﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ScrumTable.Common;
using ScrumTable.Common.Collections;
using ScrumTable.DL.Data.Common;
using ScrumTable.DL.Data.Generic.Cache;

#endregion

namespace ScrumTable.DL.Data.Generic
{
    /// <summary>
    /// The field defintion data access object encapsulates all service routines in order
    /// to access data from an external system.
    /// </summary>
    /// <remarks>The implementation of the data object class follows the Data Access Object pattern.</remarks>
    internal class MetaDataAccessObject : DataAccessObjectBase
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new MetaDataAccessObject instance, no public constructor
        /// needed.
        /// </summary>
        internal MetaDataAccessObject(GenericDataContextBase context)
            : base(context)
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new IDataObject below the given parent id chain.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <returns>Returns the created object.</returns>
        public override IDataObject Insert(ValueChain<string> parentIdChain)
        {
            // not supported (yet)
            return null;
        }

        /// <summary>
        /// Moves a IDataObject using the given id into a new parent object.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <param name="toMove">Specifies the data object to move inside the data storage.</param>
        /// <param name="newParentIdChain">Specifies the new parent id chain.</param>
        public override void Update(ValueChain<string> parentIdChain, IDataObject toMove, ValueChain<string> newParentIdChain)
        {
            // not supported (yet)
        }

        /// <summary>
        /// Retrieves all data objects which are stored in conjunction
        /// with the specified arguments.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <returns>Returns the retrieved data objects.</returns>
        public override ICollection<IDataObject> GetAll(ValueChain<string> parentIdChain)
        {
            PreCondition.AssertNotNull(parentIdChain, "parentIdChain");

            using (DataAccessSection data = EnterDataAccessSection(parentIdChain))
            {
                if (data.CurrentProject != null && parentIdChain.Count > 1)
                {
                    IEnumerable fieldDefinitions = GetFieldDefinitions(data.CurrentProject, parentIdChain[1]);

                    if (fieldDefinitions != null)
                    {
                        return fieldDefinitions.ConvertIf<IDataObject, CacheFieldDefinition>(
                            fieldDef => (fieldDef.Schema == null || !fieldDef.Schema.IsSchemaReference),
                            InitMetaDataObject);
                    }
                }
                return new IDataObject[0];
            }
        }

        /// <summary>
        /// Retrieves all data objects which are stored in the current dao.
        /// The structure of the given data objects is defined as follows:
        /// <example>
        /// <code>
        ///  [Parent Id Chain 1] -> Child Instance 1
        ///                      -> Child Instance 2
        ///                      -> Child Instance n
        /// 
        ///  [Parent Id Chain 2] -> Child Instance 3
        ///                      -> Child Instance 4
        ///                      -> Child Instance x
        /// </code>
        /// </example>
        /// </summary>
        /// <returns>Returns the retrieved data objects.</returns>
        public override IEnumerable<KeyValuePair<ValueChain<string>, ICollection<IDataObject>>> GetAll()
        {
            IDictionary<ValueChain<string>, ICollection<IDataObject>> all =
                new Dictionary<ValueChain<string>, ICollection<IDataObject>>();

            using (DataAccessSection data = EnterDataAccessSection())
            {
                foreach (CacheProject project in data.Connection.DataCache.Projects)
                {
                    foreach (CacheWorkItemType cacheWorkItemType in project.WorkItemTypes)
                    {
                        ValueChain<string> wiTypeUniqueId = new ValueChain<string>(project.UniqueId, cacheWorkItemType.UniqueId);
                        all[wiTypeUniqueId] = GetAll(wiTypeUniqueId);
                    }

                    foreach (CacheReport cacheReport in project.Reports)
                    {
                        ValueChain<string> reportUniqueId = new ValueChain<string>(project.UniqueId, cacheReport.UniqueId);
                        all[reportUniqueId] = GetAll(reportUniqueId);
                    }
                }
            }
            return all;
        }

        /// <summary>
        /// Gets a single data object by its unqiue id.
        /// </summary>
        /// <param name="parentIdChain">Global unique ids of the parent objects.</param>
        /// <param name="id">Id of the data object.</param>
        /// <returns>Returns the retieved element or a null pointer, if it could not be found.</returns>
        public override IDataObject GetById(ValueChain<string> parentIdChain, string id)
        {
            using (DataAccessSection data = EnterDataAccessSection(parentIdChain))
            {
                if (data.CurrentProject == null || parentIdChain.Count < 2)
                    return null;

                CacheFieldDefinition field = GetFieldDefinition(data.CurrentProject, parentIdChain[1], id);

                if (field != null)
                {
                    return InitMetaDataObject(field);
                }
            }
            return null;
        }

        private CacheFieldDefinition GetFieldDefinition(CacheProject parentProject, string parentId, string id)
        {
            ICacheElementList fieldDefs = GetFieldDefinitions(parentProject, parentId);

            if (fieldDefs != null)
            {
                return fieldDefs.TryGetById<CacheFieldDefinition>(id);
            }
            return null;
        }

        private ICacheElementList GetFieldDefinitions(CacheProject parentProject, string parentId)
        {
            #region Search DataObject by workitem type.

            CacheWorkItemType foundItemType = parentProject.WorkItemTypes.TryGetById(parentId);

            if (foundItemType != null)
            {
                return foundItemType.FieldDefinitions;
            }

            #endregion

            #region Search DataObject by report.

            CacheReport foundReport = parentProject.Reports.TryGetById(parentId);

            if (foundReport != null)
            {
                return foundReport.FieldDefinitions;
            }

            #endregion

            return null;
        }

        private MetaDataObject InitMetaDataObject(CacheFieldDefinition fieldDefinition)
        {
            return new MetaDataObject(this, fieldDefinition);
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}